package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//检查登录拦截器
@Component
public class CheckLoginInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private IUserInfoCacheService userInfoCacheService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //1.静态资源直接放行,当handle对象是HandlerMethod类型时表示当前访问的是Conroller上的方法
        if (! (handler instanceof HandlerMethod)) {
            return true;
        }

        //2.不需要登录的资源直接放行
        HandlerMethod hm = (HandlerMethod) handler;
        if (!hm.hasMethodAnnotation(RequiredLogin.class)) {
            return true;
        }

        //3.取出当前登录的用户
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Consts.USER_INFO);
        if (user != null) { //已经登录
            return true;
        }

        //4.从redis中去登录用户
        Cookie[] cs = request.getCookies();
        if (cs != null) {
            for (Cookie c : cs) {
                if (c.getName().equals(Consts.USER_INFO_TOKEN)) {
                    //取出token
                    String token = c.getValue();
                    String userInfo = userInfoCacheService.getUserInfo(token);
                    if (userInfo != null) {
                        //存入session
                        session.setAttribute(Consts.USER_INFO, JSON.parseObject(userInfo, UserInfo.class));
                        return true;
                    }
                }
            }
        }

        //5.没有登录,回到登录界面
        response.sendRedirect("/login.html");
        return false;
    }
}
